<?php

class Controller_Cart extends Controller_Website
{
	protected $allowedSection = array('shop');

	public function  before()
	{
//		if(empty($_SESSION)) {
//			session_start();
//		}
		parent::before();
		$this->db = Database::instance();
		$this->mod = Model::factory('Directory');
		$this->section = 'shop';
	}

	public function actionAdd($action, $id)
	{
                
            
		$section = $this->section;
		if (Request::$isAjax) {
				$response['errors'] = array();
				$item = $this->db->query('SELECT * FROM `directoryItems` WHERE `isCategory`=0 AND `id`=?', array($id))->fetch();

				if(!$item or !in_array($item['section'], $this->allowedSection)) {
					$response['errors'][] = 'Invalid id. Refresh page and try again.';
				}

				if (empty($response['errors'])) {
					switch($action) {
						case 'set':

							if (empty($_POST['color']) || empty($_POST['size']) ) {
								$response['errors'][] = 'No color or size. Refresh page and try again.';
								break;
							}
                                                        
                                                        
							if (!isset($_SESSION['cart'][$section])) {
								$_SESSION['cart'][$section] = array();
							}
                                                        
                                                        foreach ($_SESSION['cart'][$section] as $k => $v) {
								if ($v['id'] == $_POST['id'] && $v['settings']['color'] == $_POST['color'] && $v['settings']['size'] == $_POST['size']) {

                                                                $_SESSION['cart'][$section][$k]['quantity']++;
                                                                $response['errors'][] = 'This is already in cart.';
                                                                $itemsCount = 0;
                                                                foreach ($_SESSION['cart']['shop'] as $shopItem){
                                                                    $itemsCount+=$shopItem['quantity'];
                                                                }
                                                                if($itemsCount > 99){
                                                                    $itemsCount = '99+';
                                                                }
                                                                $response['eRquantity'] = $itemsCount;
                                                                break(2);
								}
							}

								$_SESSION['cart'][$section][] = array(
									'id'		=> $_POST['id'],
									'name'		=> $_POST['name'],
									'price'		=> mb_substr($_POST['price'], 0, -4,'UTF-8'),
                                                                        'token'		=> $item['token'],
                                                                        'text'		=> $item['text1'],
                                                                        'color'		=> $_POST['color'],
                                                                        'size'		=> $_POST['size'],
                                                                        'quantity'      => 1,
                                                                        'section'       => 'shop',
                                                                        'settings'      => array('size' =>$_POST['size'],
                                                                                                'color' =>$_POST['color'])
								);


                            $itemsCount = 0;
                            foreach ($_SESSION['cart']['shop'] as $shopItem){
                                $itemsCount+=$shopItem['quantity'];
                            }
                            if($itemsCount > 99){
                                $itemsCount = '99+';
                            }
                                                        $response['success'] = $itemsCount;
							break;
					}
				}

				if (!count($response['errors'])) {
					unset($response['errors']);
				}
				$this->autoRender = false;
				$this->response->setHeader('Content-Type', 'application/json');
				$this->response->body = json_encode($response);
		} else {
			$this->response->redirect('/commerce/checkout/');
		}
	}

	public function actionCart()
	{
            if(Request::$isAjax)
            {
                
                $this->autoRender = FALSE;
                 $total = 0;
                 $id = 0;
                 echo "<div class='cart_items_all'>";
                 if(empty($_SESSION['cart']['shop']))
                 {
                     echo "<div class='cart_header'>
                                <h1>Your Cart is Empty</h1>
                                <span class='cart_close'></span>
                            </div>";
                     exit;
                 }
                
                    print <<<HERE
   
   

                            <div class="cart_header">
                                <h1>Your Cart</h1>
                                <span class="cart_close"></span>
                            </div>
                            <div class="cart_fields">
                                <span class="field_description">Description</span>
                                <span class="field_delivery">	Estimated Delivery</span>
                                <span class="field_time">Time Remaining</span>
                                <span class="field_price">Price</span>
                                <span class="field_quantity">Quantity</span>
                                <span class="field_subtotal">Subtotal</span>
                                <div class="clear"></div>
                            </div>
                            
                            <div class="cart_items_wrapper">
HERE;
                    foreach ($_SESSION['cart']['shop'] as $key=>$item)
                    {
                        $total = $total + $item['price']*$item['quantity'];
                        $subtotal = $item['price']*$item['quantity'];
print <<<HERE
                        
                        <div class="cart_item" data-id="{$item['id']}">
                                    <div class="cart_item_image">
                                        <img src="{$this->manager->getImageForCartUrl($item['id'])}"/>
                                    </div>
                                    <div class="cart_item_border_wrapper">
                                        <div class="cart_item_description">
                                        <h3>{$item['name']}</h3>
                                        <p>Size: <span class='item_span_size'>{$item['settings']['size']}</span><br/>
                                            Color:<span class='item_span_color'>{$item['settings']['color']}</span>
                                        </p>
                                        <h4>Non-Returnable</h4>
                                    </div>
                                    <div class="cart_item_delivery">01/19/12 to 01/23/12</div>
                                    <div class="cart_item_time">This Item is no longer reserved</div>
                                    <div class="cart_item_price">{$item['price']}</div>
                                    <div class="cart_item_quantity">

                                    <input type="text" size="1" value="{$item['quantity']}"/><img src="/images/galochka1.png"/>
                                    </div>
                                    <div class="cart_item_subtotal">{$subtotal}</div>
                                    <div class="cart_item_remove">
                                        <span class="cart_item_remove_btn" id="{$key}"></span>
                                    </div>
                                    <div class="clear"></div>
                                    </div>
                                    <div class="clear"></div>
                                </div>
   
HERE;
                    }
 
print <<<HERE
   
                            </div>
                            <div class="cart_total">
                                Order Subtotal: <span> {$total}</span>
                            </div>
                            <div class="cart_button proceed_checkout">
                                Proceed to checkout
                            </div>
                            
                            <div class="cart_button continue_shopping">
                                Continue Shopping
                            </div>
                            <script type='text/javascript'>
                            $(function()
                                {
                                        $('.cart_items_wrapper').jScrollPane({scrollbarWidth:5,verticalDragMaxHeight:100,verticalDragMinHeight:25,contentWidth:950,verticalGutter:5});
                                }); 
                            </script>
HERE;

                          
                
                
            }
	}

	public function actionFlush()
	{
		if (Request::$isAjax) {
			$this->autoRender = false;
			$this->response->setHeader('Content-Type', 'application/json');
			$_SESSION['cart'][$this->section] = array();
			$this->response->body = json_encode('Done!');
		}
	}

	//public function actionDeleteItem()
//	{
//            $this->autoRender = false;
//            if(Request::$isAjax)
//            {
//                $id = $_POST['id'];
//                if(isset($_SESSION['cart'][$this->section][$id])) 
//                    {
//                        unset($_SESSION['cart'][$this->section][$id]);
//                    }
//                $response['success'] = count($_SESSION['cart'][$this->section]);
//            }
//            
//	}

    public function actionCartDeleteItem()
	{
            $this->autoRender = false;
            if(Request::$isAjax)
            {
                $total =0;
                $quant=0;
                $id = $_POST['id'];
                if(isset($_SESSION['cart'][$this->section][$id])) 
                    {
                        unset($_SESSION['cart'][$this->section][$id]);
                    }
                $response['success'] = count($_SESSION['cart'][$this->section]);
                
                foreach ($_SESSION['cart']['shop'] as $key=>$item)
                {
                    $total = $total + $item['price']*$item['quantity'];
                    $quant+=$_SESSION['cart']['shop'][$key]['quantity'];
                }
                $response['total'] = $total;
                $response['quant'] = $quant;
            }
            $this->response->setHeader('Content-Type', 'application/json');
            $this->response->body = json_encode($response);
            
	}
        
        public function actionQuantity()
	{
            $this->autoRender = false;
            if(Request::$isAjax)
            {
                $quantity = $_POST['quantity'];
                $id = $_POST['id'];
                if(isset($_SESSION['cart'][$this->section][$id])) 
                    {
                        $_SESSION['cart'][$this->section][$id]['quantity'] = $quantity;
                    }
                $response['success'] = count($_SESSION['cart'][$this->section]);
            }
            
	}
    public function actionCartUpdate()
    {
        if(Request::$isAjax)
        {
            $this->autoRender = FALSE;
            $total = 0;
            $quant = 0;
            foreach ($_SESSION['cart']['shop'] as $key=>$item)
                    {
                        $cartInfo['items'][$key] = $item;
                        
                        $imgurl = $this->manager->getImageForCartUrl($item['id']);
                        $cartInfo['items'][$key]['imgurl']=$imgurl;
                        $total = $total + $item['price']*$item['quantity'];
                        $subtotal = $item['price']*$item['quantity'];
                        $quant+=$_SESSION['cart']['shop'][$key]['quantity'];
                    }
                    $cartInfo['total']=$total;
                    $cartInfo['quant']=$quant;
                    
        }
        
        $this->response->setHeader('Content-Type', 'application/json');
	$this->response->body = json_encode($cartInfo);
        
        
    }
}

